﻿using System.IO;
using System.Text;
using UnityEngine;

namespace Gdmec.Util
{
    public class JsonUtil
    {

        /// <summary>
        /// 格式化json对象
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="text"></param>
        /// <returns></returns>
        public static T FromJson<T>(string text)
        {
            T t = JsonUtility.FromJson<T>(text);
            return t;
        }

        /// <summary>
        /// 保存创建json文件
        /// </summary>
        /// <param name="outPath"></param>
        /// <param name="jsonData"></param>
        public static void CreateJsonFile(string outPath, object jsonData)
        {
            using (FileStream fs = new FileStream(outPath, FileMode.Create, FileAccess.ReadWrite))
            {
                Encoding encode = new System.Text.UTF8Encoding(false);
                string json = JsonUtility.ToJson(jsonData);
                using (StreamWriter sw = new StreamWriter(fs, encode))
                {
                    sw.WriteLine(json);
                    sw.Flush();
                }
            }
        }

        /// <summary>
        /// 读取json文件
        /// </summary>
        /// <param name="filePath"></param>
        /// <returns></returns>
        public static string ReadJsonText(string filePath)
		{
			using (FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read))
			{
				using (StreamReader sr = new StreamReader(fs))
				{
					string s = sr.ReadToEnd();
					return s;
				}
			}
		}
    }
}
